package com.example.service;

import com.example.utils.Tools;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class FileMgr {
    final static Map<String,String> mimeType = new HashMap<String, String>() {
        {
            put("doc","application/msword");
            put("docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            put("xls","application/vnd.ms-excel");
            put("xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            put("ppt","application/vnd.ms-powerpoint");
            put("pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation");
            put("pdf","application/pdf");
            put("js","application/javascript");
            put("go","text/plain");
        }
    };
    static Map<String,Map<String,String>> FilesMap=new HashMap<String,Map<String,String>>();
    public static Map<String,Map<String,String>> queryFileList() {
        return FilesMap;
    }

    public static Map<String,String> queryfile(String docId) {
        return FilesMap.get(docId);
    }

    public static void loadFiles(){
        try {
            ArrayList<String> files=Tools.getFiles("classpath:storage");
            for(int i = 0;i < files.size(); i ++){
                String filePath = files.get(i);
                String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
                String ext = fileName.substring(fileName.lastIndexOf(".")+1);
                File file = new File(filePath);
                if (file.isFile()) {
                    Map<String,String> fileInfo = new HashMap<String, String>();
                    fileInfo.put("docId",Long.toHexString(Tools.crc32(filePath)));
                    fileInfo.put("title", fileName);
                    fileInfo.put("mime_type",mimeType.get(ext));
                    fileInfo.put("storage", filePath);

                    FilesMap.put(fileInfo.get("docId"),fileInfo);
                }
            }
        }catch (Exception e){
            System.out.println(e.toString());
        }
    }
}
